
#include "gmsc.h"
#include <snake.h>
#include <QPainter>

#include <QDebug>
#include <QTimer>
#include <QKeyEvent>

gmsc::gmsc(QWidget *parent)
    : QWidget{parent}
{

    this->setAttribute(Qt::WA_DeleteOnClose, true);
    this->setWindowTitle("snake");
    this->setFixedSize(QSize(1500, 780));

    this->snake = new Snake(randx(0.33 * this->width(), 0.66 * width()), randy(0.33 * this->height(), 0.66 * this->height()), this);


    dtime = 240;
    this->snake->setactivetime(dtime);
    this->snake->setmovespeed(10);
    this->snake->addboudary(this->width(), this->height());

    block = new Block(randx(0, width()), randy(0, height()), 23, 23, this);
    this->snake->addblock(block);


    this->faillabel = new QLabel(this);
    QPixmap pix;
    pix.load(":/defeat.png");
    faillabel->setPixmap(pix);
    faillabel->setFixedSize(pix.width(), pix.height());
    faillabel->move( (width()-faillabel->width()) * 0.5 , (height() - faillabel->height()) * 0.5);
    faillabel->hide();

    connect(block, &Block::re_changeloc, [=](){

        block->setRect(randx(0, width() - block->width()), randy(0, height() - block->height()), 23, 23);

    });

    connect(&timer, &QTimer::timeout, [=](){

        update();//图像的重绘
    });

    connect(snake, &Snake::fail, this, &gmsc::end);


}

void gmsc::paintEvent(QPaintEvent *e) {
    QPainter painter(this);
    QPixmap pix;
    pix.load(":/grass.png");
    painter.drawPixmap(0, 0, this->width(), this->height(), pix);

    QPen pen;
    QBrush brush;
    pen.setColor(Qt::black);
    brush.setColor(Qt::darkMagenta);
    brush.setStyle(Qt::SolidPattern);
    painter.setPen(pen);
    painter.setBrush(brush);

    snake->paintsnake(painter);
    painter.drawRect(*block);
    return QWidget::paintEvent(e);
}

void gmsc::keyPressEvent(QKeyEvent *ev)
{
    if(gameend == 1) {
        return QWidget::keyPressEvent(ev);

    }
    switch(ev->key()){

    case Qt::Key_Space:
        if(!gameStart){
            this->start();

        }else {
            this->stop();
        }
        break;
    default:
        snake->changedirect(ev);
        break;
    }

}

void gmsc::start()
{
    gameStart = true;
    timer.start(dtime);
    snake->start();

}

void gmsc::stop()
{
    gameStart = false;
    timer.stop();
    snake->stop();

}

int gmsc::randx(qreal minn, qreal maxx)
{
    return QRandomGenerator::global()->bounded((int)(minn), (int)(maxx));
}

int gmsc::randy(qreal minn, qreal maxx)
{
    return QRandomGenerator::global()->bounded((int)(minn), (int)(maxx));
}

void gmsc::end()
{
    gameend = 1;
    timer.stop();
    snake->stop();
    faillabel->show();

}
